package org.example.utils;

import io.jsonwebtoken.Claims;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;

public class SecurityContextUtil {

    /**
     * 通过SpringSecurity的上下文获取用户的token,得到id
     * @return
     */
    public static Long getCurrentUserId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) return null;
        String token = (String) authentication.getCredentials();
        if (!StringUtils.hasText(token)){
            return null;
        }
        Claims claims = JwtUtil.decryptToken(token);
        if (claims == null){
            return null;
        }
        return Long.valueOf(claims.getId());
    }
}
